package com.sto.stoapp.db.manager;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.entity.ProblemEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

public class SelectProblemManager extends StoDataBase {

	public SelectProblemManager(Context context){
		super(context);
	}
	
	/**
	 * 查询数据
	 * 
	 * @return
	 */
	public List<ProblemEntity> query(String sql, String [] args, ProblemEntity Entity) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			List<ProblemEntity> data = new ArrayList<ProblemEntity>();
			try {
			data = getDataFromCursor(getSqliteDatabase(
					UnifiedStaticType.READ_DATABASE).rawQuery(sql,
							args), Entity);
			}catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("query", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return data;
		}
	}
	
	/**
	 * 通过游标获取表的数据
	 * @param c
	 * @param Entity
	 * @return
	 */
	private List<ProblemEntity> getDataFromCursor(final Cursor c,
			ProblemEntity Entity) {
		List<ProblemEntity> listData = new ArrayList<ProblemEntity>();
		try {
			if (c != null) {
				if (c.moveToFirst()) {
					do {
						listData.add(getSingleData(c, Entity));
					} while (c.moveToNext());
				}
				closeCursor(c);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("getDataFromCursor", e.getMessage());
		} finally {
			closeCursor(c);
			closeDb(UnifiedStaticType.READ_DATABASE);
		}

		return listData;
	}
	
	@SuppressLint("NewApi")
	private ProblemEntity getSingleData(Cursor c, ProblemEntity Entity) {
		ProblemEntity data = new ProblemEntity();
		//编号
		data.setTypeCode(c.getString(c.getColumnIndex(TYPE_CODE)));
	
		//名称
		data.setTypeName(c.getString(c.getColumnIndex(TYPE_NAME)));
	
		//代号
		data.setReasonCode(c.getString(c.getColumnIndex(REASON_CODE)));
	
		//内容
		data.setReasonDetail(c.getString(c.getColumnIndex(REASON_NAME)));
	
		return data;
	}
	
}
